package com.heima.search.listen;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mrchen
 * @date 2022/7/17 11:25
 */
@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleSearchService articleSearchService;

    @Autowired
    ArticleFeign articleFeign;

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void handleUpMsg(String articleId){
        log.info("接收到文章上架 消息  文章id:{}" ,articleId);
        ResponseResult<SearchArticleVO> result = articleFeign.findArticle(Long.valueOf(articleId));
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        SearchArticleVO articleVO = result.getData();
        // 索引库添加文章
        articleSearchService.saveArticle(articleVO);

    }
    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handledDownMsg(String articleId){
        log.info("接收到文章下架 消息  文章id:{}" ,articleId);
        articleSearchService.deleteArticle(articleId);
    }
}
